import smtplib
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText


class Email(object):
    def __init__(self ,to_user ,send_user = '252816187@qq.com' ,password = 'qwrqokixfmbabhde'  ,character = 'utf-8' ,h_character = 'utf-8'):
        self.to_user = to_user
        self.send_user = send_user
        self.character = character
        self.h_character = h_character
        self.password = password
        self.smtp_server = 'smtp.qq.com'

    def plain(self ,msg ,title):
        self.msg = MIMEText(msg ,'plain' ,self.character)
        self.msg['From'] = Header(self.send_user)
        self.msg['To'] = Header(self.to_user)
        self.msg['Subject'] = Header(title ,self.h_character)

    def html(self ,msg ,title ,name):
        self.msg = MIMEMultipart()
        self.msg.attach(MIMEText(msg ,'html' ,self.h_character))
        self.addFile(name)
        self.msg['From'] = Header(self.send_user)
        self.msg['To'] = Header(self.to_user)
        self.msg['Subject'] = Header(title, self.h_character)

    def addFile(self ,name ,computer_character = 'base64' ,character = 'utf8'):
        att = MIMEText(open(name ,'rb').read() ,computer_character ,character)
        att['Content-Type'] = 'application/octet-stream'
        att['Content-Disposition'] = 'attachment; filename="测试文件"'
        self.msg.attach(att)

    def send_ssl(self ,port = 465):
        try:
            with smtplib.SMTP_SSL(self.smtp_server ,port) as sm:
                sm.login(self.send_user ,self.password)
                sm.sendmail(self.send_user ,self.to_user ,self.msg.as_string())
            return True
        except Exception as e:
            return e.__str__()

